<template>
  <div class="page-login">
    <div class="page-login--layer page-login--layer-area">
      <ul class="circles">
        <li v-for="n in 10" :key="n"></li>
      </ul>
    </div>
    <div
      class="page-login--layer page-login--layer-time"
      flex="main:center cross:center"
    >
      {{ time }}
    </div>
    <div class="page-login--layer">
      <div
        class="page-login--content"
        flex="dir:top main:justify cross:stretch box:justify"
      >
        <div class="page-login--content-header">
          <p class="page-login--content-header-motto">
            时间是一切财富中最宝贵的财富
          </p>
        </div>
      </div>
    </div>
    <!-- from表单 -->
    <div flex="dir:bottom main:center cross:center">
      <div class="sign-card">
        <!-- <div class="sign-img"><img src="./images/1.png" alt=""></div> -->
        <!-- <div class="separated">
            <div class="left"></div>
          <div class="right"></div>
         </div> -->
        <h1 style="text-align: center">电子云警察</h1>
        <div class="sign-from">
          <t-form
            style="width: 400px; position: absolute; left: -35px"
            :data="formData"
            :rules="rules"
            @submit="onSubmit"
          >
            <t-form-item name="username">
              <t-input
                clearable
                v-model="formData.username"
                placeholder="请输入用户名"
              >
                <desktop-icon slot="prefix-icon"></desktop-icon>
              </t-input>
            </t-form-item>
            <t-form-item name="password">
              <t-input
                type="password"
                clearable
                v-model="formData.password"
                placeholder="请输入密码"
              >
                <lock-on-icon slot="prefix-icon"></lock-on-icon>
              </t-input>
            </t-form-item>
            <t-form-item name="confirm">
              <t-input
                type="password"
                clearable
                v-model="formData.confirm"
                placeholder="请确认密码"
              >
                <lock-on-icon slot="prefix-icon"></lock-on-icon>
              </t-input>
            </t-form-item>
            <t-form-item name="email">
              <t-input
                clearable
                v-model="formData.email"
                placeholder="请输入邮箱"
              >
                <mail-icon slot="prefix-icon"></mail-icon>
              </t-input>
            </t-form-item>
            <t-form-item name="code">
              <t-input
                clearable
                v-model="formData.code"
                placeholder="请输入邮箱码"
              >
                <code-icon slot="prefix-icon"></code-icon>
              </t-input>
              <t-button
                style="margin-left: 10px"
                @click="getCode"
                :disabled="disable"
              >
                {{ codeStr }}
              </t-button>
            </t-form-item>

            <t-form-item style="padding-top: 8px">
              <t-button theme="primary" type="submit" block>注册用户</t-button>
            </t-form-item>
          </t-form>
          <!--  -->
          <div style="position: absolute; bottom: 100px; left: 137px">
            <router-link to="/login" style="color: #409eff">
              已有账户？立即登录
            </router-link>
          </div>
          <!--  -->
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import dayjs from "dayjs";
import { DesktopIcon, LockOnIcon, MailIcon, CodeIcon } from "tdesign-icons-vue";

const INITIAL_DATA = {
  username: "",
  password: "",
  confirm: "",
  email: "",
  code: "",
};

export default {
  name: "sign",
  mounted() {
    this.timeInterval = setInterval(() => {
      this.refreshTime();
    }, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timeInterval);
  },
  components: {
    DesktopIcon,
    LockOnIcon,
    MailIcon,
    CodeIcon,
  },
  data() {
    return {
      timeInterval: null,
      codeStr: "获取验证码",
      disable: false,
      time: dayjs().format("HH:mm:ss"),
      formData: { ...INITIAL_DATA },
      rules: {
        username: [
          { required: true, message: "用户名必填", type: "error" },
          {
            min: 8,
            message: "至少需要两个字符，一个中文等于两个字符",
            type: "warning",
          },
          { max: 20, message: "用户名字符长度超出", type: "warning" },
          {
            pattern: /\w+/,
            message: "用户名必须有字母、数字",
            type: "warning",
          },
        ],
        password: [
          { required: true, message: "密码必填", type: "error" },
          {
            pattern:
              /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
            message: "密码必须有大小写字母和数字",
            type: "warning",
          },
          {
            min: 8,
            message: "至少需要八个字符，一个中文等于两个字符",
            type: "warning",
          },
          { max: 20, message: "用户名字符长度超出20", type: "warning" },
        ],
        confirm: [
          {
            validator: (val) => this.formData.password === val,
            message: "必须和密码相同",
          },
        ],
        email: [
          { required: true, message: "邮箱必填", type: "error" },
          {
            email: { ignore_max_length: true },
            message: "邮箱输入不正确",
            type: "warning",
          },
        ],
        code: [{ required: true }],
      },
    };
  },
  beforeUpdate() {
    // 验证码反复申请
    if (this.codeStr <= 60) {
      this.codeStr -= 1;
      this.disable = true;
    }
    if (this.codeStr === 0) {
      this.codeStr = "重新获取验证码";
      this.disable = false;
    }
  },
  methods: {
    refreshTime() {
      this.time = dayjs().format("HH:mm:ss");
    },
    // 邮箱获取验证码
    async getCode() {
      this.codeStr = 60;
      const res = await fetch("/api/user/register/sendEmail", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ mail: this.formData.email }),
      }).then((data) => {
        if (data.ok === true) this.$message.success("邮箱发送成功，请注意查收");
        else this.$message.error("请填写正确的邮箱");
      });
    },
    onSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        const { username, password, email, code } = this.formData;
        const res = fetch("/api/user/register", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            username: username,
            password: password,
            email: email,
            code: code,
          }),
        })
          .then((data) => data.json())
          .then((resp) => {
            switch (resp.code) {
              case 200:
                this.$message.success("提交成功");
                this.$store.state.d2admin.user.username = username;
                this.$router.push({ name: "login" });
                break;
              case 500:
                this.$message.error(`${resp.message}`);
                this.codeStr = "重新获取验证码";
                this.disable = false;
                break;
            }
          });
      } else {
        console.log("Errors: ", validateResult);
        this.$message.warning(firstError);
      }
    },
  },
};
</script>
<style scoped>
.sign-card {
  margin: auto;
  margin-top: 150px;
  width: 400px;
  height: 600px;
  border: 2px solid rgba(95, 128, 152, 0.4);
  /* display: flex; */
  /* background: linear-gradient(210deg, transparent 1.5em, rgba(250, 250, 250,0.5) 0); */
  background-color: rgba(250, 250, 250, 0.5);
  /* min-width:600px; */
  /* padding: 20px; */
  border-radius: 10px;
  position: relative;
}
/* .sign-card::after{
  content: '';
  height: 10px;
  width: 46%;
  position: absolute;
  left: 0;
  top: 0;
 background:linear-gradient(to right, rgba(45, 255, 150, 0) , rgba(45, 255, 150, 0.2));
} */
/* .sign-img{
    width: 40%;
}
.sign-img img{
    width: 100%;
} */
.sign-from {
  /* display: flex; */
  padding-top: 50px;
}
.separated {
  position: absolute;
  top: 0;
  bottom: 0;
  /* left: 45%; */
}
/* .left{
  width: 9px;
			height: 100%;
      float: left;
      background:linear-gradient(to right, rgba(43, 43, 43, 0) , rgba(43, 43, 43, 0.2));
}
.right{
height: 100%;
		width: 25px;
       float: left;
			background:linear-gradient(to right, rgba(0, 0, 0, .25) , rgba(0,0,0,0));
			overflow: hidden;
} */
</style>